package com.huaboot.system.strategy.impl;

import com.huaboot.commont.exception.BusinessException;
import com.huaboot.system.entity.SysObjectStoreEntity;
import com.huaboot.system.enums.UploadModeEnum;
import com.huaboot.system.service.SysObjectStoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * @description: 本地项目上传策略实现类
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProjectUploadStrategyImpl extends AbstractUploadStrategyImpl {

    private final SysObjectStoreService objectStoreService;

    /**
     * 本地项目端口
     */
    @Value("${server.port}")
    private Integer port;


    private SysObjectStoreEntity objectStore;

    @Override
    public void initClient() {
        //一件事把数据库里的保存路径初始化到objectStore注入
        objectStore = objectStoreService.getObjectStoreByLabel(UploadModeEnum.PROJECT_UPLOAD.getMode());
        log.info("Local Project Init Success...");
    }

    @Override
    public boolean checkFileIsExisted(String fileRelativePath, String fileName) {
        return new File(objectStore.getDomainUrl() +File.separator+ fileRelativePath + File.separator + fileName).exists();
    }

    @Override
    public void executeUpload(MultipartFile file, String fileRelativePath, String fileName) throws IOException {
        File dest = checkFolderIsExisted(fileRelativePath);
        try {
            file.transferTo(new File(dest + "/" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
    }

    @Override
    public String getPublicNetworkAccessUrl(String fileRelativePath, String fileName) {
        try {
            String host = InetAddress.getLocalHost().getHostAddress();
            return String.format("http://%s:%d/%s/%s", host, port, objectStore.getDomainUrl(), fileRelativePath + fileName);
        } catch (UnknownHostException e) {
            throw new BusinessException("未知异常");
        }
    }

    /**
     * 检查文件夹是否存在，若不存在则创建文件夹，最终返回上传文件
     * @param fileRelativePath 文件相对路径
     * @return {@link  File} 文件
     */
    private File checkFolderIsExisted(String fileRelativePath) {
        File rootPath = new File(objectStore.getDomainUrl() + File.separator + fileRelativePath);
        if (!rootPath.exists()) {
            if (!rootPath.mkdirs()) {
                throw new BusinessException("文件夹创建失败");
            }
        }
        return rootPath;
    }

}
